package com.xb.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xb.model.domain.entity.PaymentOrder;
import com.xb.model.domain.entity.RechargeRecord;
import com.xb.model.domain.entity.VipPackage;
import com.xb.system.common.result.Result;
import com.xb.system.service.PaymentService;
import com.xb.system.service.RechargeRecordService;
import com.xb.system.service.VipPackageService;
import com.xb.system.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/quota")
public class VipPackageController {
    @Autowired
    private RechargeRecordService rechargeRecordService;
    @Autowired
    private VipPackageService vipPackageService;
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/userPackage")
    public Result<Object> getUserPackage() {
        Long userId = UserContext.getUserId();
        VipPackage vipPackage = vipPackageService.getUserPackage(userId);
        
        // 补偿机制：如果用户没有套餐，检查是否有已支付但未处理的订单
        if (vipPackage == null || (vipPackage.getTotalQuota() == 0 && "无套餐".equals(vipPackage.getPackageType()))) {
            log.info("用户没有套餐，检查是否有已支付但未处理的订单: userId={}", userId);
            
            // 1. 先查询用户自己的已支付订单
            List<PaymentOrder> paidOrders = paymentService.getUserPaymentRecords(userId);
            for (PaymentOrder order : paidOrders) {
                // 只处理已支付但可能未处理充值的订单
                if (order.getStatus() == 1 && order.getPayTime() != null) {
                    log.info("发现已支付订单，尝试补偿处理: orderNo={}, userId={}, amount={}", 
                            order.getOrderNo(), userId, order.getAmount());
                    
                    try {
                        // 调用补偿处理方法
                        boolean success = paymentService.compensateOrder(order.getOrderNo());
                        if (success) {
                            log.info("补偿处理订单成功: orderNo={}, userId={}", order.getOrderNo(), userId);
                            
                            // 重新查询套餐
                            vipPackage = vipPackageService.getUserPackage(userId);
                            if (vipPackage != null && vipPackage.getTotalQuota() > 0) {
                                log.info("补偿处理成功，找到套餐: userId={}, totalQuota={}", userId, vipPackage.getTotalQuota());
                                return Result.ok(vipPackage);
                            }
                        } else {
                            log.warn("补偿处理订单失败: orderNo={}, userId={}", order.getOrderNo(), userId);
                        }
                    } catch (Exception e) {
                        log.error("补偿处理订单异常: orderNo={}, userId={}", order.getOrderNo(), userId, e);
                    }
                }
            }
            
            // 2. 如果还没找到套餐，查询userId=0的已支付订单（匿名用户订单）
            // 这些订单可能是用户未登录时创建的，现在登录后需要关联
            // 只处理最近的订单（按创建时间倒序，只处理第一个）
            try {
                List<PaymentOrder> anonymousOrders = paymentService.getUserPaymentRecords(0L);
                log.info("查询到{}个匿名用户订单，当前登录用户userId={}", anonymousOrders.size(), userId);
                
                // 只处理最近的已支付订单（按创建时间倒序）
                for (PaymentOrder order : anonymousOrders) {
                    // 只处理已支付但可能未处理充值的订单
                    if (order.getStatus() == 1 && order.getPayTime() != null) {
                        log.info("发现匿名用户已支付订单，尝试补偿处理并关联到当前用户: orderNo={}, orderUserId=0, currentUserId={}, amount={}, payTime={}", 
                                order.getOrderNo(), userId, order.getAmount(), order.getPayTime());
                        
                        try {
                            // 先更新订单的userId为当前登录用户
                            order.setUserId(userId);
                            boolean updateSuccess = paymentService.updateOrder(order);
                            if (!updateSuccess) {
                                log.error("更新订单userId失败: orderNo={}, userId={}", order.getOrderNo(), userId);
                                continue;
                            }
                            log.info("已将订单userId从0更新为当前用户: orderNo={}, userId={}", order.getOrderNo(), userId);
                            
                            // 然后调用补偿处理方法
                            boolean success = paymentService.compensateOrder(order.getOrderNo());
                            if (success) {
                                log.info("补偿处理匿名订单成功: orderNo={}, userId={}", order.getOrderNo(), userId);
                                
                                // 重新查询套餐
                                vipPackage = vipPackageService.getUserPackage(userId);
                                if (vipPackage != null && vipPackage.getTotalQuota() > 0) {
                                    log.info("补偿处理成功，找到套餐: userId={}, totalQuota={}", userId, vipPackage.getTotalQuota());
                                    return Result.ok(vipPackage);
                                }
                            } else {
                                log.warn("补偿处理匿名订单失败: orderNo={}, userId={}", order.getOrderNo(), userId);
                            }
                            
                            // 只处理第一个订单，避免重复处理
                            break;
                        } catch (Exception e) {
                            log.error("补偿处理匿名订单异常: orderNo={}, userId={}", order.getOrderNo(), userId, e);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("查询匿名用户订单失败: userId={}", userId, e);
            }
        }
        
        if (vipPackage != null) {
            return Result.ok(vipPackage);
        } else {
            // 创建默认套餐信息
            VipPackage defaultPackage = new VipPackage();
            defaultPackage.setUserId(userId);
            defaultPackage.setPackageType("无套餐");
            defaultPackage.setTotalQuota(0);
            defaultPackage.setUsedQuota(0);
            defaultPackage.setStartTime(LocalDateTime.now());
            return Result.ok(defaultPackage);
        }
    }

    @GetMapping("/rechargeRecords")
    public Result<Object> getRechargeRecords() {
        Long userId = UserContext.getUserId();
        // 查询用户的充值记录
        List<RechargeRecord> records = rechargeRecordService.list(new QueryWrapper<RechargeRecord>()
                .eq("user_id", userId)
                .eq("is_deleted", 0)
                .orderByDesc("transfer_time"));
        return Result.ok(records);
    }




}